define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'order/index' + location.search,
                    add_url: 'order/add',
                    multi_url: 'order/multi',
                    import_url: 'order/import',
                    table: 'order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                escape: false,
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},
                        {field: 'order_sn', title: __('Order_sn'), operate: 'LIKE'},
                        {field: 'user.nickname', title: __('User'), operate: 'LIKE'},
                        {field: 'project.name', title: __('Project'), operate: 'LIKE'},
                        {field: 'quantity', title: __('Quantity'), sortable: true},
                        {field: 'unit_price', title: __('Unit_price'), operate: 'BETWEEN', sortable: true},
                        {field: 'discount', title: __('Discount'), operate: 'BETWEEN', sortable: true, formatter: function(value) {
                                return (value * 100).toFixed(0) + '%';
                            }},
                        {field: 'total_amount', title: __('Total_amount'), operate: 'BETWEEN', sortable: true, formatter: Table.api.formatter.amount},

                        {
                            field: 'handlers_badge',
                            title: __('Handlers'),
                            operate: false,
                            formatter: function(value, row, index) {
                                return value || '<span class="label label-default">无打手</span>';
                            }
                        },

                        {field: 'handler_amount', title: __('Handler_amount'), operate: 'BETWEEN', sortable: true, formatter: Table.api.formatter.amount},
                        {field: 'start_time', title: __('Start_time'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'end_time', title: __('End_time'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'status', title: __('Status'), searchList: {"0":__('Cancelled'),"1":__('Pending'),"2":__('In Progress'),"3":__('Completed')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},

                        {
                            field: 'buttons',
                            width: "120px",
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'ajax',
                                    text: '取消',
                                    title: __('Set to Cancelled'),
                                    classname: 'btn btn-xs btn-danger btn-ajax',
                                    icon: 'fa fa-delone',
                                    url: 'order/changeStatus/status/0',
                                    confirm: '确认取消订单？',
                                    refresh: true,
                                    visible: function (row) {
                                        if (row.status==1){ return true};
                                        return false;
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                                {
                                    name: 'ajax',
                                    text: '开始',
                                    title: __('Set to In Progress'),
                                    classname: 'btn btn-xs btn-info btn-ajax',
                                    icon: 'fa fa-leaf',
                                    url: 'order/changeStatus/status/2',
                                    confirm: '确认开始订单？',
                                    refresh: true,
                                    visible: function (row) {
                                        if (row.status==1){ return true};
                                        return false;
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                                {
                                    name: 'ajax',
                                    text: '完成',
                                    title: __('Set to Completed'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'order/changeStatus/status/3',
                                    confirm: '确认完成订单？',
                                    refresh: true,
                                    visible: function (row) {
                                        if (row.status==2){ return true};
                                        return false;
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                }
                            ],
                            formatter: Table.api.formatter.buttons
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            // 添加自定义事件处理
            Controller.api.bindevent();
        },


        add: function () {
            // 添加页面特有的事件绑定
            Controller.api.bindAddEvent();
        },

        api: {
            bindevent: function () {
                var self = this;
                // 绑定状态变更按钮事件 - 修复这里
                $(document).on('click', '.btn-change-status', function(e) {
                    e.stopPropagation();
                    var id = $(this).data('id');
                    var status = $(this).data('status');
                    self.changestatus(id, status);
                });

                // 绑定表单事件
                Form.api.bindevent($("form[role=form]"));
            },

            // 添加页面特有的事件绑定
            bindAddEvent: function() {
                // 调用通用事件绑定
                this.bindevent();

                // 添加页面特有的事件
                this.bindAddPageEvents();
            },

            // 添加页面事件处理
            bindAddPageEvents: function() {
                var self = this;

                // 项目选择变化事件
                $(document).on("change", "#c-project_id", function(e) {
                    var selectedValue = $(this).val();
                    if (selectedValue) {
                        // 根据data-source属性手动请求数据
                        var dataSource = 'project/detail'; // "project/index"
                        $.ajax({
                            url: dataSource,
                            type: 'GET',
                            data: {
                                id: selectedValue,
                                // 可能需要其他参数
                            },
                            success: function(response) {
                                if (response && response.data) {
                                    var projectData = response.data;
                                    self.handleProjectChange(e, projectData);
                                }
                            }
                        });}
                });

                // 单价变化事件
                $(document).on("input", "#c-unit_price", function() {
                    self.calculateTotalAmount();
                });
                // 数量变化事件
                $(document).on("input", "#c-quantity", function() {
                    self.calculateTotalAmount();
                });

                // 折扣变化事件
                $(document).on("input", "#c-discount", function() {
                    self.calculateTotalAmount();
                });

                // 初始化selectpage组件
                this.initSelectPage();
            },

            // 处理项目选择变化
            handleProjectChange: function(e,data) {
                $('#c-unit_price').val(data.default_price);
                $('#price-help').text('当前项目: ' + data.name + ' - ¥' + data.default_price + '/' + (data.unit || ''));
                this.calculateTotalAmount();


            },

            // 计算总金额
            calculateTotalAmount: function() {
                var quantity = parseFloat($('#c-quantity').val()) || 0;
                var unitPrice = parseFloat($('#c-unit_price').val()) || 0;
                var discount = parseFloat($('#c-discount').val()) || 1.00;

                // 计算总金额（数量 × 单价 × 折扣）
                var totalAmount = quantity * unitPrice * discount;

                // 更新总金额字段
                $('#c-total_amount').val(totalAmount.toFixed(2));

                // 更新帮助文本
                $('#amount-help').text('计算: ' + quantity + ' × ' + unitPrice.toFixed(2) + ' × ' + discount + ' = ¥' + totalAmount.toFixed(2));
            },

            // 初始化selectpage组件
            initSelectPage: function() {
                if (typeof $.fn.selectpage !== 'undefined') {
                    $('#c-project_id').selectpage({
                        formatter: function(item) {
                            return item.name + ' - ¥' + (item.default_price || item.price || '0.00') + '/' + (item.unit || '');
                        }
                    });

                    // 初始化其他selectpage组件
                    $('.selectpage').not('#c-project_id').selectpage();
                }
            },
        }
    };

    return Controller;
});